import rarfile
import random
import time
import sys

wrong_password = []


class MyIterator:
    # 单位字符集合
    letters = '0123456789'
    digits = 0

    def __init__(self, digits):
        # 密码位数范围
        self.digits = digits

    # 迭代器
    def __iter__(self):
        return self

    def __next__(self):
        rst = ""
        while rst == "" or rst in wrong_password:
            for length in range(0, self.digits):
                rst += random.choice(MyIterator.letters)
        return rst


def extract(filename):
    start_time = time.time()
    file = rarfile.RarFile(".\\" + filename)
    # 解压文件名字

    for p in MyIterator(4):
        try:
            file.extractall(path=".", pwd=str(p).encode('utf-8'))
            # 文件地址"."说明当前文件夹
            print("Password: {}".format(p))
            now_time = time.time()
            print("Spend time: {}".format(now_time - start_time))
            sys.exit(0)
        except Exception as e:
            wrong_password.append(p)
            print('Error', p)
            pass


if __name__ == '__main__':
    filename = input("Input filename: ")
    extract(filename)
